package com.develop.vo;

import java.io.IOException;

public class MsgHeadUtils {
	public static byte[] intToBytes2(int value) {
		byte[] src = new byte[4];
		src[0] = (byte) (value >> 24 & 0xFF);
		src[1] = (byte) (value >> 16 & 0xFF);
		src[2] = (byte) (value >> 8 & 0xFF);
		src[3] = (byte) (value & 0xFF);
		return src;
	}

	public static int bytesToInt2(byte[] src, int offset) {
		int value = (src[offset] & 0xFF) << 24 | (src[(offset + 1)] & 0xFF) << 16 | (src[(offset + 2)] & 0xFF) << 8 | src[(offset + 3)] & 0xFF;

		return value;
	}

	public static byte[] shortToBytes2(short value) {
		byte[] src = new byte[2];
		src[0] = (byte) (value >> 8 & 0xFF);
		src[1] = (byte) (value & 0xFF);
		return src;
	}

	public static short bytesToShort2(byte[] src, int offset) {
		short value = (short) ((src[offset] & 0xFF) << 8 | src[(offset + 1)] & 0xFF);

		return value;
	}

	public static byte[] byteToBytes2(byte value) {
		byte[] src = new byte[1];
		src[0] = value;
		return src;
	}

	public static byte bytesToByte(byte[] src, int offset) {
		byte value = src[offset];
		return value;
	}

	public static void main(String[] args) throws IOException {
		String strBody = "reqLogin;user=yiy;key=qw#$@;type=msg";
		byte[] allMessage = new byte[9 + strBody.length()];
		short startSign = -1;
		byte msgType = 1;
		int timeStamp = (int) (System.currentTimeMillis() / 1000L);
		short bodyLen = (short) strBody.length();
		System.arraycopy(shortToBytes2(startSign), 0, allMessage, 0, 2);
		System.arraycopy(byteToBytes2(msgType), 0, allMessage, 2, 1);
		System.arraycopy(intToBytes2(timeStamp), 0, allMessage, 3, 4);
		System.arraycopy(shortToBytes2(bodyLen), 0, allMessage, 7, 2);
		System.arraycopy(strBody.getBytes(), 0, allMessage, 9, strBody.length());

		System.out.println("startSign=" + startSign + ",msgType=" + msgType + ",timeStamp=" + timeStamp + ",bodyLen=" + bodyLen + ",strBody=" + strBody);

		short startSignParser = bytesToShort2(allMessage, 0);
		byte msgTypeParser = bytesToByte(allMessage, 2);
		int timeStampParser = bytesToInt2(allMessage, 3);
		short bodyLenParser = bytesToShort2(allMessage, 7);
		byte[] bodyParser = new byte[bodyLenParser];
		System.arraycopy(allMessage, 9, bodyParser, 0, bodyLenParser);
		String bodyParserStr = new String(bodyParser);

		System.out.println("startSignParser=" + startSignParser + ",msgTypeParser=" + msgTypeParser + ",timeStampParser=" + timeStampParser + ",bodyLenParser=" + bodyLenParser + ",bodyParserStr=" + bodyParserStr);
	}
}